package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.SupplierDao;
import com.atguigu.jxc.domain.ErrorCode;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.domain.SuccessCode;
import com.atguigu.jxc.entity.Log;
import com.atguigu.jxc.entity.Supplier;
import com.atguigu.jxc.service.LogService;
import com.atguigu.jxc.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gwk
 * @create 2021 -09 -04 13:50
 */
@Service
public class SupplierServiceImpl implements SupplierService {

    @Autowired
    SupplierDao supplierDao;
    @Autowired
    LogService logService;

    @Override
    public Map<String, Object> list(Integer page, Integer rows, String supplierName) {
        Map<String, Object> map = new HashMap<>();
        page = page == 0 ? 1 : page;
        int offSet = (page - 1)*rows;
        List<Supplier> supplierList = supplierDao.getList(offSet, rows, supplierName);

        logService.save(new Log(Log.SELECT_ACTION,"分页查询供应商信息"));

        map.put("total",supplierDao.getTotal(supplierName));
        map.put("rows",supplierList);

        return map;
    }

    @Override
    public ServiceVO save(Supplier supplier) {
        // 供应商ID为空时，说明是新增操作，需要先判断供应商名字是否存在
        if (supplier.getSupplierId() == null){
            Supplier exSupplier = supplierDao.findSupplierByName(supplier.getSupplierName());
            if (exSupplier != null){
                return new ServiceVO(ErrorCode.ACCOUNT_EXIST_CODE,ErrorCode.ACCOUNT_EXIST_MESS);
            }
            supplierDao.addSupplier(supplier);
            logService.save(new Log(Log.INSERT_ACTION,"添加供应商："+supplier.getSupplierName()));
        } else {
            supplierDao.updateSupplier(supplier);
            logService.save(new Log(Log.UPDATE_ACTION,"修改供应商:"+supplier.getSupplierName()));
        }
        return new ServiceVO<>(SuccessCode.SUCCESS_CODE,SuccessCode.SUCCESS_MESS);
    }

    @Override
    public ServiceVO delete(String ids) {
        String[] split = ids.split(",");
        List<String> list = Arrays.asList(split);
        supplierDao.delete(list);
        logService.save(new Log(Log.DELETE_ACTION,"删除供应商:"));
        return new ServiceVO(SuccessCode.SUCCESS_CODE,SuccessCode.SUCCESS_MESS);
    }


}
